package com.hjq.fcloud.ui.activity

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.widget.AdapterView
import android.widget.GridView
import android.widget.ImageView
import android.widget.TextView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.hjq.bar.TitleBar
import com.hjq.fcloud.R
import com.hjq.fcloud.action.TitleBarAction
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.app.AppApplication
import com.hjq.fcloud.bean.FncItemBean
import com.hjq.fcloud.bean.ProjectItemBean
import com.hjq.fcloud.config.SystemSet
import com.hjq.fcloud.http.Urls
import com.hjq.fcloud.http.api.AllProjectListApi
import com.hjq.fcloud.http.api.FncListApi
import com.hjq.fcloud.http.api.InitAppApi
import com.hjq.fcloud.http.api.ProjectListApi
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.jump.CommonJump
import com.hjq.fcloud.jump.CommonJumpBean
import com.hjq.fcloud.ktx.ViewKtx.setVisibility
import com.hjq.fcloud.other.AppConfig
import com.hjq.fcloud.other.MainDrawerListener
import com.hjq.fcloud.other.QrCodeParse
import com.hjq.fcloud.ui.adapter.FncDrawerAdapter
import com.hjq.fcloud.ui.adapter.ProjectDrawerAdapter
import com.hjq.fcloud.utils.AppConfigUtils
import com.hjq.fcloud.utils.DrawableUtils
import com.hjq.fcloud.utils.EmptyViewUtil
import com.hjq.fcloud.utils.FileUtils
import com.hjq.fcloud.utils.GlideUtils
import com.hjq.fcloud.utils.Logger
import com.hjq.fcloud.utils.StringSplitter
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallback
import com.huawei.hms.ml.scan.HmsScan
import com.xuexiang.xupdate.XUpdate
import com.zhy.adapter.abslistview.CommonAdapter
import com.zhy.adapter.abslistview.ViewHolder
import kotlinx.android.synthetic.main.activity_main.demandLv
import kotlinx.android.synthetic.main.activity_main.demandTitleBar
import kotlinx.android.synthetic.main.activity_main.drawerLayout
import kotlinx.android.synthetic.main.activity_main.drawerLayoutChild
import kotlinx.android.synthetic.main.activity_main.projectLv
import kotlinx.android.synthetic.main.layout_main_content.buildCorpNameTv
import kotlinx.android.synthetic.main.layout_main_content.codeTv
import kotlinx.android.synthetic.main.layout_main_content.fncTypeNameTv
import kotlinx.android.synthetic.main.layout_main_content.mRecyclerView
import kotlinx.android.synthetic.main.layout_main_content.mainStateLayout
import kotlinx.android.synthetic.main.layout_main_content.redPointView
import kotlinx.android.synthetic.main.layout_main_content.scanTv
import kotlinx.android.synthetic.main.layout_main_content.sectNameTv
import kotlinx.android.synthetic.main.layout_main_content.settingTv
import kotlinx.android.synthetic.main.layout_main_content.switchIv
import okhttp3.Call

class MainActivity : AppActivity() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var mExitTime: Long = 0
    private var projectList: ArrayList<ProjectItemBean>? = null
    private var fncList: ArrayList<FncItemBean>? = null

    //选中的项目
    private var selectProjectBean: ProjectItemBean? = null

    //选中的需求
    private var selectFncItem: FncItemBean? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun getStateLayout(): View? {
        return mainStateLayout
    }

    override fun initView() {
        //自定义EmptyView
        mLoadingAndRetryManager?.mLoadingAndRetryLayout?.setEmptyView(R.layout.layout_main_empty_view)

        //禁止测滑
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        drawerLayoutChild.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)

        scanTv.setOnClickListener {
            jumpScanPage()
        }

        settingTv.setOnClickListener {
            startActivity(SettingActivity::class.java)
        }
    }

    private fun jumpScanPage() {
        startActivityForResult(CommonScanActivity::class.java, object : OnActivityCallback {
            override fun onActivityResult(resultCode: Int, data: Intent?) {
                var obj = data?.getParcelableExtra<HmsScan>(CommonScanActivity.SCAN_RESULT)
                var showResult = obj?.showResult
                if(resultCode == RESULT_OK){
                    QrCodeParse.perforomQrCodeParse(this@MainActivity,showResult)
                }
            }
        })


    }

    override fun initData() {
        update()

        getServerValidProjectList()
    }

    override fun clickRetry() {
        super.clickRetry()
        initData()
    }

    /**
     * 获取有效的项目（存在需求的项目）
     */
    private fun getServerValidProjectList() {
        showAppLoading()
        EasyHttp.post(this)
            .api(ProjectListApi())
            .request(object : HttpCallback<HttpData<ArrayList<ProjectItemBean>>?>(this) {
                override fun onSucceed(data: HttpData<ArrayList<ProjectItemBean>>?) {
                    var projectList = data?.getData()
                    if (projectList != null && projectList!!.size > 0) {
                        var cacheSelectProjectBean = AppConfigUtils.getSelectProjectItemBean()
                        //判断缓存有数据并且在项目中，才使用缓存中数据，否则取接口的第一个
                        if (cacheSelectProjectBean != null && existValidProjectList(
                                cacheSelectProjectBean,
                                projectList
                            )
                        ) {
                            getServerAllProjectList(cacheSelectProjectBean)
                        } else {
                            getServerAllProjectList(projectList.get(0))
                        }
                    } else {
                        toast(R.string.string_project_empty)
                        showAppEmpty()
                    }
                }

                private fun existValidProjectList(
                    cacheSelectProjectBean: ProjectItemBean,
                    projectList: java.util.ArrayList<ProjectItemBean>
                ): Boolean {
                    projectList.forEach {
                        if (it.project_id.equals(cacheSelectProjectBean?.project_id)) {
                            return true
                        }
                    }
                    return false
                }

                override fun onStart(call: Call?) {
//                    super.onStart(call)
                }

                override fun onFail(e: java.lang.Exception?) {
                    super.onFail(e)
                    showAppRetry(e?.message)
                }
            })
    }

    /**
     * 获取所有的项目
     */
    private fun getServerAllProjectList(selectProjectBean: ProjectItemBean) {
        EasyHttp.post(this)
            .api(AllProjectListApi())
            .request(object : HttpCallback<HttpData<ArrayList<ProjectItemBean>>?>(this) {
                override fun onSucceed(data: HttpData<ArrayList<ProjectItemBean>>?) {
                    projectList = data?.getData()
                    setProjectDrawerViewData(selectProjectBean)
                    getServerFncList(selectProjectBean, {})
                }

                override fun onStart(call: Call?) {
//                    super.onStart(call)
                }

                override fun onFail(e: java.lang.Exception?) {
                    super.onFail(e)
                    showAppRetry(e?.message)
                }
            })
    }


    private fun getServerFncList(
        projectItemBean: ProjectItemBean,
        callBack: () -> Unit,
        showLoading: Boolean = false
    ) {
        EasyHttp.post(this)
            .api(FncListApi(projectItemBean?.project_id))
            .request(object : HttpCallback<HttpData<ArrayList<FncItemBean>>?>(this) {
                override fun onSucceed(data: HttpData<ArrayList<FncItemBean>>?) {
                    fncList = data?.getData()
                    if (fncList != null && fncList!!.size > 0) {
                        showAppContent()

                        selectProjectBean = projectItemBean

                        var cacheFnc =
                            AppConfigUtils.getSelectProjectItemBean()?.selectFncItemBean//缓存中的需求
                        var selectFnc: FncItemBean
                        if (cacheFnc != null && existValidFncList(cacheFnc, fncList!!)) {//判断缓存有数据并且在项目中，才使用缓存中数据，否则取接口的第一个
                            selectFnc = cacheFnc!!
                        } else {
                            selectFnc = fncList!!.get(0)
                        }

                        setFncDrawerViewData(selectFnc)

                        getServerMenuData()

                        callBack()
                    } else {
                        toast(R.string.string_fnc_empty)
                        showAppEmpty()
                    }
                }


                private fun existValidFncList(
                    cacheSelectFncBean: FncItemBean?,
                    fncList: ArrayList<FncItemBean>
                ): Boolean {
                    fncList.forEach {
                        if (it.id.equals(cacheSelectFncBean?.id)) {
                            return true
                        }
                    }
                    return false
                }

                override fun onStart(call: Call?) {
                    if (showLoading) {
                        super.onStart(call)
                    }
                }

                override fun onFail(e: java.lang.Exception?) {
                    super.onFail(e)
                    showAppRetry(e?.message)
                }
            })
    }

    private fun setHeaderViewData(fncItemBean: FncItemBean?) {
        selectFncItem = fncItemBean
        selectProjectBean?.selectFncItemBean = fncItemBean

        AppConfigUtils.saveSelectProjectItemBean(selectProjectBean)

        redPointView.setVisibility(selectFncItem?.task_count!! > 0)

        fncTypeNameTv.setText(selectFncItem?.fncTypeName)
        //动态设置背景
        DrawableUtils.setTextStyleByStyle(
            fncTypeNameTv,
            fncTypeNameTv.text.toString(),
            "#078d5c"
        )
        codeTv.setText(selectFncItem?.code)
        buildCorpNameTv.setText(selectProjectBean?.project_name)
        sectNameTv.setText(selectFncItem?.sect_name)
        switchIv.setOnClickListener { drawerLayout.openDrawer(Gravity.LEFT) }
    }

    /**
     * 抽屉-需求
     */
    private fun setFncDrawerViewData(selectFnc: FncItemBean) {
        setHeaderViewData(selectFnc)

        demandTitleBar.setOnTitleBarListener(object : TitleBarAction {
            override fun getTitleBar(): TitleBar? {
                return demandTitleBar
            }

            override fun onLeftClick(view: View) {
                drawerLayoutChild.closeDrawers()
            }
        })
        var adapter = FncDrawerAdapter(context, fncList)
        adapter.setDrawerItemClickListener(object : MainDrawerListener {
            override fun onSelect(index: Int, item: Any) {
                drawerLayoutChild.closeDrawers()
                drawerLayout.closeDrawers()

                setHeaderViewData(fncList?.get(index))
            }
        })
        demandLv.adapter = adapter
        adapter.setSelection(demandLv, selectFnc)
    }

    /**
     * 抽屉-项目
     */
    private fun setProjectDrawerViewData(selectProjectBean: ProjectItemBean?) {
        var adapter = ProjectDrawerAdapter(context, projectList)
        adapter.setDrawerItemClickListener(object : MainDrawerListener {
            override fun onSelect(index: Int, item: Any) {
                getServerFncList(projectList!!.get(index), {
                    drawerLayoutChild.openDrawer(Gravity.LEFT)
                }, true)
            }
        })
        projectLv.adapter = adapter
        adapter.setSelection(projectLv, selectProjectBean)
    }

    /**
     * 升级功能
     */
    private fun update() {
        val mUpdateUrl: String = AppConfig.getHostUrl() + Urls.UPDATE_URL
        XUpdate.newBuild(activity)
            .updateUrl(mUpdateUrl)
            .update()
    }


    override fun onRestart() {
        super.onRestart()
        getServerMenuData()
    }

    private fun getServerMenuData() {
        EasyHttp.post(this)
            .api(InitAppApi(selectFncItem?.id))
            .request(object : HttpCallback<HttpData<InitAppApi.RetJson>?>(this) {
                override fun onSucceed(data: HttpData<InitAppApi.RetJson>?) {
                    SystemSet.config = data?.getData()
                    setAdapter(data?.getData()?.menu)
                }

                override fun onStart(call: Call?) {
//                    super.onStart(call)
                }
            })
    }

    private fun setAdapter(meuns: ArrayList<InitAppApi.RetJson.Mean>?) {
        var list = ArrayList<String>()
        list.add("")
        //实例化匿名内部类
        var mAdapter =
            object : BaseQuickAdapter<String, BaseViewHolder>(
                R.layout.home_rv_item,
                list
            ) {
                override fun convert(helper: BaseViewHolder, item: String) {
                    var titleView = helper.getView<TextView>(R.id.id_title_tv)
                    titleView.setText("需求管理")

                    var subGridView: RecyclerView = helper.getView(R.id.id_sub_gv)

                    setChildAdapter(meuns, subGridView, helper.position)
                }
            }
        mAdapter?.setEmptyView(EmptyViewUtil.getEmptyView(context, null))
        mRecyclerView?.setAdapter(mAdapter)
    }

    fun setChildAdapter(
        children: ArrayList<InitAppApi.RetJson.Mean>?,
        subGridView: RecyclerView,
        parentPos: Int
    ) {
        if (children != null && children.size > 0) {
            var subAdapter =
                object : BaseQuickAdapter<InitAppApi.RetJson.Mean,BaseViewHolder>(
                    R.layout.home_sub_rv_item,
                    children
                ) {
                    override fun convert(subHolder: BaseViewHolder, item: InitAppApi.RetJson.Mean) {
                        var subTv = subHolder.getView<TextView>(R.id.id_sub_tv)
                        subTv.setText(StringSplitter.splitAndJoinString(item.title,6,"\n"))

                        var imageView = subHolder.getView<ImageView>(R.id.id_sub_iv);
                        GlideUtils.loadImage(
                            context,
                            imageView,
                            item.getIcon()
                        )

                        var count = item.message
                        var countTv = subHolder.getView<TextView>(R.id.countTv);
                        if (count > 0) {
                            countTv.visibility = View.VISIBLE
                            countTv.setText(count.toString())
                        } else {
                            countTv.visibility = View.GONE
                        }
                    }

                }
            subGridView.adapter = subAdapter
            subGridView.layoutManager = GridLayoutManager(context,4)
            subAdapter.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener {
                override fun onItemClick(p0: BaseQuickAdapter<*, *>?, p1: View?, p2: Int) {
                    try {
                        var item = children.get(p2)
                        if (item.biz_code.equals(CommonJump.COMMON_JUMP_CODE_MWC)
                            || item.biz_code.equals(CommonJump.COMMON_JUMP_CODE_IMAGE_UPLOAD)
                        ) {
                            CommonListActivity.launcher(context!!, item.menu_id, item.biz_code)
                        } else {
                            var jumpBean = CommonJumpBean()
                            jumpBean.bizId = selectFncItem?.id
                            jumpBean.setBizCode(item.biz_code)
                            jumpBean.isStartSign = true
                            CommonJump.commonJump(this@MainActivity, jumpBean)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        showToast("数据异常")
                    }
                }
            })
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                showToast("再按一次退出应用")
                mExitTime = System.currentTimeMillis()
                return true
            } else {
                exitApp()

            }
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exitApp() {
        FileUtils.clearCacheFile(context)
        AppApplication.mContext?.exit()
        //System.exit(0);
        //android.os.Process.killProcess(android.os.Process.myPid());
    }
}